<?php
/**
 * Created by PhpStorm.
 * User: Mo
 * Date: 15-6-10
 * Time: 上午11:11
 */

/**
 * 获得文章分类下的文章列表
 *
 * @access  public
 * @param   integer $cat_id
 * @param   integer $page
 * @param   integer $size
 *
 * @return  array
 */
function get_cat_articles($cat_id, $page = 1, $size = 20, $requirement = '')
{
    //取出所有非0的文章
    if ($cat_id == '-1') {
        $cat_str = 'cat_id > 0';
    } else {
        $cat_str = get_article_children($cat_id);
    }
    //增加搜索条件，如果有搜索内容就进行搜索
    if ($requirement != '') {
        $sql = 'SELECT article_id, title, author, add_time, file_url, open_type' .
            ' FROM ' . \ECS::table('article') .
            ' WHERE is_open = 1 AND title like \'%' . $requirement . '%\' ' .
            ' ORDER BY article_type DESC, article_id DESC';
    } else {

        $sql = 'SELECT article_id, title, author, add_time, file_url, open_type' .
            ' FROM ' . \ECS::table('article') .
            ' WHERE is_open = 1 AND ' . $cat_str .
            ' ORDER BY article_type DESC, article_id DESC';
    }

    $res = Ecdb::selectLimit($sql, $size, ($page - 1) * $size);

    $arr = array();
    if ($res) {
        while ($row = Ecdb::fetchRow($res)) {
            $article_id = $row['article_id'];

            $arr[ $article_id ]['id'] = $article_id;
            $arr[ $article_id ]['title'] = $row['title'];
            $arr[ $article_id ]['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ? sub_str($row['title'],
                $GLOBALS['_CFG']['article_title_length']) : $row['title'];
            $arr[ $article_id ]['author'] = empty($row['author']) || $row['author'] == '_SHOPHELP' ? $GLOBALS['_CFG']['shop_name'] : $row['author'];
            $arr[ $article_id ]['url'] = $row['open_type'] != 1 ? build_uri('article', array('aid' => $article_id), $row['title']) : trim($row['file_url']);
            $arr[ $article_id ]['add_time'] = date($GLOBALS['_CFG']['date_format'], $row['add_time']);
        }
    }

    return $arr;
}

/**
 * 获得指定分类下的文章总数
 *
 * @param   integer $cat_id
 *
 * @return  integer
 */
function get_article_count($cat_id, $requirement = '')
{
    global $db, $ecs;
    if ($requirement != '') {
        $count = $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('article') . ' WHERE ' . get_article_children($cat_id) . ' AND  title like \'%' . $requirement . '%\'  AND is_open = 1');
    } else {
        $count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('article') . " WHERE " . get_article_children($cat_id) . " AND is_open = 1");
    }
    return $count;
}

/**
 * ECSHOP 加密解密类
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: lib_code.php 17217 2011-01-19 06:29:08Z liubo $
 */


/**
 * 加密函数
 * @param   string $str 加密前的字符串
 * @param   string $key 密钥
 * @return  string  加密后的字符串
 */
function encrypt($str, $key = AUTH_KEY)
{
    $coded = '';
    $keylength = strlen($key);

    for ($i = 0, $count = strlen($str); $i < $count; $i += $keylength) {
        $coded .= substr($str, $i, $keylength) ^ $key;
    }

    return str_replace('=', '', base64_encode($coded));
}

/**
 * 解密函数
 * @param   string $str 加密后的字符串
 * @param   string $key 密钥
 * @return  string  加密前的字符串
 */
function decrypt($str, $key = AUTH_KEY)
{
    $coded = '';
    $keylength = strlen($key);
    $str = base64_decode($str);

    for ($i = 0, $count = strlen($str); $i < $count; $i += $keylength) {
        $coded .= substr($str, $i, $keylength) ^ $key;
    }

    return $coded;
}


/**
 * 获得当前格林威治时间的时间戳
 *
 * @return  integer
 */
function gmtime()
{
    return (time() - date('Z'));
}

/**
 * 获得服务器的时区
 *
 * @return  integer
 */
function server_timezone()
{
    if (function_exists('date_default_timezone_get')) {
        return date_default_timezone_get();
    } else {
        return date('Z') / 3600;
    }
}


/**
 *  生成一个用户自定义时区日期的GMT时间戳
 *
 * @access  public
 * @param   int $hour
 * @param   int $minute
 * @param   int $second
 * @param   int $month
 * @param   int $day
 * @param   int $year
 *
 * @return void
 */
function local_mktime($hour = null, $minute = null, $second = null, $month = null, $day = null, $year = null)
{
    $timezone = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone'];

    /**
     * $time = mktime($hour, $minute, $second, $month, $day, $year) - date('Z') + (date('Z') - $timezone * 3600)
     * 先用mktime生成时间戳，再减去date('Z')转换为GMT时间，然后修正为用户自定义时间。以下是化简后结果
     **/
    $time = mktime($hour, $minute, $second, $month, $day, $year) - $timezone * 3600;

    return $time;
}


/**
 * 将GMT时间戳格式化为用户自定义时区日期
 *
 * @param  string  $format
 * @param  integer $time 该参数必须是一个GMT的时间戳
 *
 * @return  string
 */

function local_date($format, $time = null)
{
    $timezone = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone'];

    if ($time === null) {
        $time = gmtime();
    } elseif ($time <= 0) {
        return '';
    }

    $time += ($timezone * 3600);

    return date($format, $time);
}


/**
 * 转换字符串形式的时间表达式为GMT时间戳
 *
 * @param   string $str
 *
 * @return  integer
 */
function gmstr2time($str)
{
    $time = strtotime($str);

    if ($time > 0) {
        $time -= date('Z');
    }

    return $time;
}

/**
 *  将一个用户自定义时区的日期转为GMT时间戳
 *
 * @access  public
 * @param   string $str
 *
 * @return  integer
 */
function local_strtotime($str)
{
    $timezone = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone'];

    /**
     * $time = mktime($hour, $minute, $second, $month, $day, $year) - date('Z') + (date('Z') - $timezone * 3600)
     * 先用mktime生成时间戳，再减去date('Z')转换为GMT时间，然后修正为用户自定义时间。以下是化简后结果
     **/
    $time = strtotime($str) - $timezone * 3600;

    return $time;

}

/**
 * 获得用户所在时区指定的时间戳
 *
 * @param   $timestamp  integer     该时间戳必须是一个服务器本地的时间戳
 *
 * @return  array
 */
function local_gettime($timestamp = null)
{
    $tmp = local_getdate($timestamp);
    return $tmp[0];
}

/**
 * 获得用户所在时区指定的日期和时间信息
 *
 * @param   $timestamp  integer     该时间戳必须是一个服务器本地的时间戳
 *
 * @return  array
 */
function local_getdate($timestamp = null)
{
    $timezone = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone'];

    /* 如果时间戳为空，则获得服务器的当前时间 */
    if ($timestamp === null) {
        $timestamp = time();
    }

    $gmt = $timestamp - date('Z');       // 得到该时间的格林威治时间
    $local_time = $gmt + ($timezone * 3600);    // 转换为用户所在时区的时间戳

    return getdate($local_time);
}


/**
 * UCenter 函数库
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: lib_uc.php 17217 2011-01-19 06:29:08Z liubo $
 */


/**
 * 通过判断is_feed 向UCenter提交Feed
 *
 * @access public
 * @param  integer  $value_id $order_id or $comment_id
 * @param  interger $feed_type BUY_GOODS or COMMENT_GOODS
 *
 * @return void
 */
function add_feed($id, $feed_type)
{
    $feed = array();
    if ($feed_type == BUY_GOODS) {
        if (empty($id)) {
            return;
        }
        $id = intval($id);
        $order_res = Ecdb::getAll("SELECT g.goods_id, g.goods_name, g.goods_sn, g.goods_desc, g.goods_thumb, o.goods_price FROM " . \ECS::table('order_goods') . " AS o, " . \ECS::table('goods') . " AS g WHERE o.order_id='{$id}' AND o.goods_id=g.goods_id");
        foreach ($order_res as $goods_data) {
            if (!empty($goods_data['goods_thumb'])) {
                $url = \ECS::url() . $goods_data['goods_thumb'];
            } else {
                $url = \ECS::url() . $GLOBALS['_CFG']['no_picture'];
            }
            $link = \ECS::url() . "goods.php?id=" . $goods_data["goods_id"];

            $feed['icon'] = "goods";
            $feed['title_template'] = '<b>{username} ' . $GLOBALS['_LANG']['feed_user_buy'] . ' {goods_name}</b>';
            $feed['title_data'] = array('username' => $_SESSION['user_name'], 'goods_name' => $goods_data['goods_name']);
            $feed['body_template'] = '{goods_name}  ' . $GLOBALS['_LANG']['feed_goods_price'] . ':{goods_price}  ' . $GLOBALS['_LANG']['feed_goods_desc'] . ':{goods_desc}';
            $feed['body_data'] = array('goods_name' => $goods_data['goods_name'], 'goods_price' => $goods_data['goods_price'], 'goods_desc' => sub_str(strip_tags($goods_data['goods_desc']),
                150, true));
            $feed['images'][] = array('url'  => $url,
                                      'link' => $link);
            uc_call("uc_feed_add",
                array($feed['icon'], $_SESSION['user_id'], $_SESSION['user_name'], $feed['title_template'], $feed['title_data'], $feed ['body_template'], $feed['body_data'], '', '', $feed['images']));
        }
    }
    return;
}

/**
 * 获得商品tag所关联的其他应用的列表
 *
 * @param   array $attr
 *
 * @return  void
 */
function get_linked_tags($tag_data)
{
    //取所有应用列表
    $app_list = uc_call("uc_app_ls");
    if ($app_list == '') {
        return '';
    }
    foreach ($app_list as $app_key => $app_data) {
        if ($app_data['appid'] == UC_APPID) {
            unset($app_list[ $app_key ]);
            continue;
        }
        $get_tag_array[ $app_data['appid'] ] = '5';
        $app_array[ $app_data['appid'] ]['name'] = $app_data['name'];
        $app_array[ $app_data['appid'] ]['type'] = $app_data['type'];
        $app_array[ $app_data['appid'] ]['url'] = $app_data['url'];
        $app_array[ $app_data['appid'] ]['tagtemplates'] = $app_data['tagtemplates'];
    }

    $tag_rand_key = array_rand($tag_data);
    $get_tag_data = uc_call("uc_tag_get", array($tag_data[ $tag_rand_key ], $get_tag_array));
    foreach ($get_tag_data as $appid => $tag_data_array) {
        $templates = $app_array[ $appid ]['tagtemplates']['template'];
        if (!empty($templates) && !empty($tag_data_array['data'])) {
            foreach ($tag_data_array['data'] as $tag_data) {
                $show_data = $templates;
                foreach ($tag_data as $tag_key => $data) {
                    $show_data = str_replace('{' . $tag_key . '}', $data, $show_data);
                }
                $app_array[ $appid ]['data'][] = $show_data;
            }
        }
    }

    return $app_array;
}

/**
 * 兑换积分
 *
 * @param  integer $uid 用户ID
 * @param  integer $fromcredits 原积分
 * @param  integer $tocredits 目标积分
 * @param  integer $toappid 目标应用ID
 * @param  integer $netamount 积分数额
 *
 * @return boolean
 */
function exchange_points($uid, $fromcredits, $tocredits, $toappid, $netamount)
{
    $ucresult = uc_call('uc_credit_exchange_request', array($uid, $fromcredits, $tocredits, $toappid, $netamount));
    if (!$ucresult) {
        return false;
    } else {
        return true;
    }
}
